﻿#region License
// Copyright 2010 Microsoft Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion

using System;
using System.Collections.Specialized;
using System.Globalization;
using System.Reflection;
using System.Security;
using System.Security.Principal;
using System.Threading;
using System.Collections.Generic;

namespace MediaWiki.MediaWikiConverter.Utilities.Logging
{
  public abstract class ExceptionFormatter
  {
    private static readonly IList<string> IgnoredProperties = new List<string> { "Source", "Message", "HelpLink", "InnerException", "StackTrace" };
    private readonly Exception _exception;
    private NameValueCollection _additionalInfo;

    protected ExceptionFormatter(Exception exception)
    {
      if (exception == null)
        throw new ArgumentNullException("exception");

      _exception = exception;
    }

    public NameValueCollection AdditionalInfo
    {
      get
      {
        if (_additionalInfo == null)
        {
          _additionalInfo = new NameValueCollection();
          _additionalInfo.Add("MachineName", GetMachineName());
          _additionalInfo.Add("TimeStamp", DateTime.UtcNow.ToString(CultureInfo.InvariantCulture));
          _additionalInfo.Add("FullName", Assembly.GetExecutingAssembly().FullName);
          _additionalInfo.Add("AppDomainName", AppDomain.CurrentDomain.FriendlyName);
//          _additionalInfo.Add("ThreadPrincipalType", Thread.CurrentPrincipal.GetType().FullName);
//          _additionalInfo.Add("ThreadIdentityType", Thread.CurrentPrincipal.Identity.GetType().FullName);
          _additionalInfo.Add("ThreadIdentity", Thread.CurrentPrincipal.Identity.Name);
          _additionalInfo.Add("WindowsIdentity", GetWindowsIdentity());
        }
        return _additionalInfo;
      }
    }

    public Exception Exception
    {
      get { return _exception; }
    }

    public virtual void Format()
    {
      WriteDescription();
      WriteDateTime(DateTime.UtcNow);
      WriteException(_exception, null);
    }

    private static string GetMachineName()
    {
      try
      {
        return Environment.MachineName;
      }
      catch (SecurityException)
      {
        return "Permission Denied";
      }
      catch (Exception)
      {
        return "Error";
      }
    }

    private static string GetWindowsIdentity()
    {
      try
      {
        return WindowsIdentity.GetCurrent().Name;
      }
      catch (SecurityException)
      {
        return "Permission Denied";
      }
      catch (Exception)
      {
        return "Error";
      }
    }

    protected abstract void WriteAdditionalInfo(NameValueCollection additionalInformation);
    protected abstract void WriteDateTime(DateTime utcNow);
    protected abstract void WriteDescription();

    protected virtual void WriteException(Exception exceptionToFormat, Exception outerException)
    {
      if (exceptionToFormat == null)
      {
        throw new ArgumentNullException("exceptionToFormat");
      }
      WriteExceptionType(exceptionToFormat.GetType());
      WriteMessage(exceptionToFormat.Message);
      WriteSource(exceptionToFormat.Source);
      WriteHelpLink(exceptionToFormat.HelpLink);
      WriteReflectionInfo(exceptionToFormat);
      WriteStackTrace(exceptionToFormat.StackTrace);
      if (outerException == null)
      {
        WriteAdditionalInfo(AdditionalInfo);
      }
      Exception innerException = exceptionToFormat.InnerException;
      if (innerException != null)
      {
        WriteException(innerException, exceptionToFormat);
      }
    }

    protected abstract void WriteExceptionType(Type exceptionType);
    protected abstract void WriteHelpLink(string helpLink);
    protected abstract void WriteMessage(string message);
    protected abstract void WriteMemberInfo(MemberInfo memberInfo, object value);

    protected void WriteReflectionInfo(Exception exceptionToFormat)
    {
      if (exceptionToFormat == null)
        throw new ArgumentNullException("exceptionToFormat");

      Type type = exceptionToFormat.GetType();

      List<MemberInfo> fieldsAndProperties = new List<MemberInfo>();
      fieldsAndProperties.AddRange(type.GetProperties(BindingFlags.Public | BindingFlags.Instance));
      fieldsAndProperties.AddRange(type.GetFields(BindingFlags.Public | BindingFlags.Instance));

      foreach (MemberInfo memberInfo in fieldsAndProperties)
      {
        if (!IgnoredProperties.Contains(memberInfo.Name) && CanReadMemberValue(memberInfo) && !IsIndexedProperty(memberInfo))
        {
          object value;
          try
          {
            value = GetMemberValue(memberInfo, exceptionToFormat);
          }
          catch (Exception)
          {
            value = "Access failed";
          }
          WriteMemberInfo(memberInfo, value);
        }
      }
    }

    public static bool IsIndexedProperty(MemberInfo member)
    {
      PropertyInfo property = member as PropertyInfo;
      if (property == null)
        return false;

      ParameterInfo[] parameters = property.GetIndexParameters();
      return (parameters != null && parameters.Length > 0);
    }

    public static bool CanReadMemberValue(MemberInfo member)
    {
      switch (member.MemberType)
      {
        case MemberTypes.Field:
          return true;
        case MemberTypes.Property:
          return ((PropertyInfo)member).CanRead;
        default:
          return false;
      }
    }

    public static object GetMemberValue(MemberInfo member, object target)
    {
      switch (member.MemberType)
      {
        case MemberTypes.Field:
          return ((FieldInfo)member).GetValue(target);
        case MemberTypes.Property:
          try
          {
            return ((PropertyInfo)member).GetValue(target, null);
          }
          catch (TargetParameterCountException e)
          {
            throw new ArgumentException(string.Format("MemberInfo '{0}' has index parameters", member.Name), "member", e);
          }
        default:
          throw new ArgumentException(string.Format("MemberInfo '{0}' is not of type FieldInfo or PropertyInfo", member.Name), "member");
      }
    }

    protected abstract void WriteSource(string source);
    protected abstract void WriteStackTrace(string stackTrace);
  }
}